﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Text.RegularExpressions;


namespace CCPSIP.SIP
{
    /// <summary>CCPSIP_021：取得桌機共振資訊 API</summary>
    /// idHeader = 裝置 UUID 前八碼。iOS 請使用 [CCPCrypto getIdHeader] 呼叫。
    /// checkcode = 裝置限時驗證碼。iOS 請使用 [CCPCrypto getCheckcode] 呼叫。

    public class fork_info : IHttpHandler
    {
        private const string kHQMobileExtPattern = "^" + SipKit.kHQMobileExtPrefix + "[1-9][0-9]{2}$";


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";

            try
            {
                //【01】取得POST參數，驗證身分
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_01: Cannot identify this device");//無法識別此裝置
                }


                //【02】檢查是否可設定共振
                //
                if (!Regex.IsMatch(userInfo.SIP_Num, kHQMobileExtPattern))
                {
                    throw new Exception("Error_02: You have no access right");//沒有存取權限
                }


                //【03】取得桌機共振資訊
                //
                Dictionary<string, string> resultDict = SipKit.getForkInfo(userInfo.SIP_Num);


                //【99】回傳結果
                //
                resp.ContentType = "application/json";
                resp.Charset = null;
                fastJSON.JSON.Instance.Parameters.EnableAnonymousTypes = true;
                resultStr = fastJSON.JSON.Instance.ToJSON(resultDict);
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
